Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either <a> tag or <select> tag. My purpose is to expand the select element on hover by triggering click event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<a id="linkElement" href="www.google.co.uk">click</a>
<select name="cars" id="selectElemet">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<script>
$(document).ready(function () {
$("#selectElement").mouseover(function () {
$("#selectElement").trigger("click");
});
$("#linkElement").mouseover(function () {
alert('here');
$("#linkElement").trigger("click");
});
});
</script>
</body>
</html>
.trigger("click") will not actually click the element, it will only trigger click handler attached with the element. Since you have not attached any none is triggered.
You can use native .click()
$("#selectElement").get(0).click(); //get(0) returns reference to DOM element
There'a a spelling mistake in your ID attribute. Replace 'selectElemet' to 'selectElement'. Hope that helps.
trigger('click') just happen where you have set 'click' event with element ,not physical 'click'.for example,trigger('click') even don't trigger '' tag if attach without 'click'